package com.bee.beemanage.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bee.beemanage.api.service.SysRoleMenuService;
import com.bee.beemanage.api.entity.SysRoleMenu;
import com.bee.beemanage.api.mapper.SysRoleMenuMapper;
import com.bee.beemanage.system.common.utils.result.Result;
import com.bee.beemanage.system.common.utils.result.ResultTool;
import com.bee.beemanage.system.common.utils.transaction.TransUtils;
import com.bee.beemanage.system.common.utils.transaction.Transaction;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色菜单关联表 服务实现类
 * </p>
 *
 * @author 陈国松
 * @since 2023-05-09
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public List<SysRoleMenu> getRoleMenus(String roleId) {
        //查询角色权限关联信息
        QueryWrapper<SysRoleMenu> querySysRoleMenu = Wrappers.query();
        querySysRoleMenu.eq("role_id",roleId);
        return sysRoleMenuMapper.selectList(querySysRoleMenu);
    }

    @Override
    public Result editBatch(String roleId,List<String> sysRoleMenus) {
        Result result = ResultTool.success();
        Transaction trans = null;
        try {
            trans = TransUtils.getTrans();
            trans.begin();
            List<SysRoleMenu> sysRoleMenu = new ArrayList<>();
            for (String roleMenu : sysRoleMenus) {
                SysRoleMenu sysRoleMenuT = new SysRoleMenu();
                sysRoleMenuT.setMenuId(roleMenu);
                sysRoleMenuT.setRoleId(roleId);
                sysRoleMenu.add(sysRoleMenuT);
            }
            QueryWrapper<SysRoleMenu> query = Wrappers.query();
            query.eq("role_id",roleId);
            sysRoleMenuMapper.delete(query);
            saveBatch(sysRoleMenu);
            trans.commit();
        } catch (Exception e) {
            if(null!=trans){
                trans.rollback();
            }
            result = ResultTool.fail();
            result.setErrorMsg(e.getMessage());
            return result;
        }
        return result;
    }
}
